package com.ys.web.user.friends.manager;

import com.ys.utils.base.j2se.StringHandler;
import com.ys.web.user.friends.mapper.UserFriendsMapper;
import com.ys.web.user.friends.po.UserBlackFriendsPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class FriendsManager {

    @Autowired
    private UserFriendsMapper userFriendsMapper;
    private static Map<String, List<UserBlackFriendsPO>> blackFriends = new HashMap<>();

    @PostConstruct
    void init() {
        initBlackList();
    }

    /**
     * 初始化所有黑名单
     */
    private void initBlackList() {
        List<UserBlackFriendsPO> list = userFriendsMapper.friendBlackList();
        if (StringHandler.isNotEmpty(list)) {
            blackFriends = list.stream().collect(Collectors.groupingBy(UserBlackFriendsPO::getUserId));
        }
    }

    /**
     * 添加黑名单成功，放入内存
     *
     * @param uid
     * @param friendId
     */
    public static void addBlackFriends(String uid, long friendId) {
        UserBlackFriendsPO po = new UserBlackFriendsPO();
        po.setUserId(uid);
        po.setFriendId(friendId);
        List<UserBlackFriendsPO> list = blackFriends.get(uid) == null ? new ArrayList<>() : blackFriends.get(uid);
        list.add(po);
        blackFriends.put(uid, list);
    }

    /**
     * 移出黑名单，删除内存数据
     *
     * @param uid
     * @param friendId
     */
    public static void removeBlackFriends(String uid, long friendId) {
        List<UserBlackFriendsPO> list = blackFriends.get(uid) == null ? new ArrayList<>() : blackFriends.get(uid);
        list = list.stream().filter(x -> x.getFriendId() != friendId).collect(Collectors.toList());
        blackFriends.put(uid, list);
    }

    /**
     * 根据当前用户获取黑名单列表
     *
     * @param uid
     * @return
     */
    public static List<Long> getBlackFriendsId(String uid) {
        return blackFriends.get(uid) == null ? new ArrayList<>() : blackFriends.get(uid).stream().map(UserBlackFriendsPO::getFriendId).collect(Collectors.toList());
    }

    /**
     * 判断好友是否黑名单
     *
     * @param uid
     * @param friendId
     * @return
     */
    public static long isBlackFriend(String uid, long friendId) {
        return blackFriends.get(uid) == null ? 0L : blackFriends.get(uid).stream().filter(x -> x.getFriendId() == friendId).count();
    }
}
